package com.sdruixinggroup.mondayb2b.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.API.Constants;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.adapter.MyOrderAdapter;
import com.sdruixinggroup.mondayb2b.adapter.QuickAdapter;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.AliPayBeen;
import com.sdruixinggroup.mondayb2b.models.ModelBeen;
import com.sdruixinggroup.mondayb2b.models.Order;
import com.sdruixinggroup.mondayb2b.models.UPPayBeen;
import com.sdruixinggroup.mondayb2b.models.WeiChatPayBeen;
import com.sdruixinggroup.mondayb2b.ui.Activities.AppraiseActivity;
import com.sdruixinggroup.mondayb2b.ui.OrderDetailActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.sdruixinggroup.mondayb2b.widget.OrderTabView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import okhttp3.Call;

/**
 * Created by 00029935 on 2017/12/7.
 */

public class MyOrderFragment extends BaseFragment {


    @BindView(R.id.recyclerView)
    LFRecyclerView recyclerView;
    @BindView(R.id.loading)
    ProgressBar loading;
    private ImageView tobar_left;
    private TextView topbar_center;

    private OrderTabView mTabView1;
    private OrderTabView mTabView2;
    private OrderTabView mTabView3;
    private OrderTabView mTabView4;
    private OrderTabView mTabView5;
    private OrderTabView mTabView6;
    private List<OrderTabView> mTabViewList;

    private MyOrderAdapter adapter;
    private List<Order.OrdersBean.DataBean> data;
    private int page = 1;
    private int status = 0;  //状态：0全部 1待付款 2待审核 3待发货 4待收货 5待评价
    private int index = 0;
    private IWXAPI iwxapi;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        index = getActivity().getIntent().getIntExtra("index",0);
        iwxapi = WXAPIFactory.createWXAPI(getContext(), Constants.APP_ID);
        // 将该app注册到微信
        iwxapi.registerApp(Constants.APP_ID);
    }

    @Override
    protected int getInflateLayout() {
        return R.layout.fragment_order;
    }

    @Override
    protected void setUpView(View view) {
        topbar_center = (TextView) view.findViewById(R.id.topbar_title);
        topbar_center.setText("我的订单");

        tobar_left = (ImageView) view.findViewById(R.id.topbar_left);
        tobar_left.setImageResource(R.mipmap.share_back);
        tobar_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });


        mTabView1 = (OrderTabView) view.findViewById(R.id.tab_order_1);
        mTabView2 = (OrderTabView) view.findViewById(R.id.tab_order_2);
        mTabView3 = (OrderTabView) view.findViewById(R.id.tab_order_3);
        mTabView4 = (OrderTabView) view.findViewById(R.id.tab_order_4);
        mTabView5 = (OrderTabView) view.findViewById(R.id.tab_order_5);
        mTabView6 = (OrderTabView) view.findViewById(R.id.tab_order_6);
        mTabView1.setText("全部");
        mTabView2.setText("待付款");
        mTabView3.setText("待发货");
        mTabView4.setText("待收货");
        mTabView5.setText("待评价");
        mTabView6.setText("待审核");

        mTabViewList = new ArrayList<>();
        mTabViewList.add(mTabView1);
        mTabViewList.add(mTabView2);
        mTabViewList.add(mTabView3);
        mTabViewList.add(mTabView4);
        mTabViewList.add(mTabView5);
        mTabViewList.add(mTabView6);



        for (OrderTabView tabView : mTabViewList) {
            tabView.setOnClickListener(mOnClickListener);
        }
        adapter = new MyOrderAdapter(getContext());
        data = new ArrayList<>();

        adapter.setData(data);
        recyclerView.setAdapter(adapter);
//状态：-2已关闭 -1已驳回 1待付款 2待审核 3待发货 4待收货 5待评价 6已完成 ,

        adapter.setOnOrderHandler(new MyOrderAdapter.OnOrderHandler(){
            @Override
            public void litener(Order.OrdersBean.DataBean itemData, int position) {
                int status = itemData.getStatus();
                switch (status){
                    case -2:
                        break;
                    case -1:
                        break;
                    case 1:
                        remindOrder(itemData.getId(),status,itemData);
                        break;
                    case 2:
                        break;
                    case 3:
                        remindOrder(itemData.getId(),status,itemData);
                        break;
                    case 4:
                        remindOrder(itemData.getId(),status,itemData);
                        break;
                    case 5:
                        Intent intent = new Intent(getContext(), AppraiseActivity.class);
                        intent.putExtra("ID",itemData.getId());
                       // intent.putExtra("order_goods_id",itemData.getOrder_goods().get);
                        startActivity(intent);
                        break;
                    case 6:
                        remindOrder(itemData.getId(),status,itemData);
                        break;
                }
            }
        });
        adapter.setOnItemClickListener(new QuickAdapter.OnItemClickListener<Order.OrdersBean.DataBean>(){
            @Override
            public void OnItemClick(Order.OrdersBean.DataBean data, int postion) {
                Intent intent = new Intent(getContext(),OrderDetailActivity.class);
                intent.putExtra("ID",data.getId());
                startActivity(intent);
            }
        });
        recyclerView.setRefresh(true);
        recyclerView.setLoadMore(true);
        recyclerView.setLFRecyclerViewListener(new LFRecyclerView.LFRecyclerViewListener(){
            @Override
            public void onRefresh() {
                queryData(true);
            }

            @Override
            public void onLoadMore() {
                queryData(false);
            }
        });
        setChecked(index);
    }


    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tab_order_1:
                    setChecked(0);
                    break;
                case R.id.tab_order_2:
                    setChecked(1);
                    break;
                case R.id.tab_order_3:
                    setChecked(2);
                    break;
                case R.id.tab_order_4:
                    setChecked(3);
                    break;
                case R.id.tab_order_5:
                    setChecked(4);
                    break;
                case R.id.tab_order_6:
                    setChecked(5);
                    break;
            }
        }
    };

    private void setChecked(int index) {
        for (int i = 0; i < mTabViewList.size(); i++) {
            mTabViewList.get(i).setChecked(index == i);
        }
        switch (index){
            case 0:
                status =0;
                break;
            case 1:
                status =1;
                break;
            case 2:
                status =3;
                break;
            case 3:
                status =4;
                break;
            case 4:
                status =5;
                break;
            case 5:
                status =2;
                break;
        }

        queryData(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        queryData(true);
    }

    private void queryData(final Boolean isReflush){
        if(isFirstIn ){
            isFirstIn = false;
            loading.setVisibility(View.VISIBLE);
        }

        if(isReflush){
            page = 1;
        }

        String url = API.ORDERS+"page="+page+"&page_size=10"+"&status="+status+"&access_token="+ UserInfoUtil.getInfoToken(getContext());
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");

        TypeToken<Order> typeToken = new TypeToken<Order>() {
        };

        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<Order>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {
                if(null != loading){
                    loading.setVisibility(View.GONE);
                }

                if(null != recyclerView){
                    recyclerView.stopLoadMore();
                    recyclerView.stopRefresh(true);
                }
            }

            @Override
            public void onResponse(Order response, int id) {
                if(isReflush){
                    data.clear();
                }

                if (null != response) {
                    if (response.getErr_code() == 0) {
                        List<Order.OrdersBean.DataBean> dataBeen= response.getOrders().getData();
                        if(null != dataBeen && !dataBeen.isEmpty()){
                            data.addAll(dataBeen);
                        }
                        adapter.reflashData(data);
                        ++page;
                    } else {
                        showMsgToast(response.getErr_msg());
                    }
                }

                if(null != loading){
                    loading.setVisibility(View.GONE);
                }

                if(null != recyclerView){
                    recyclerView.stopLoadMore();
                    recyclerView.stopRefresh(true);
                }
            }
        });

    }

    private void remindOrder(int id ,final int status,Order.OrdersBean.DataBean itemData){
        //状态：-2已关闭 -1已驳回 1待付款 2待审核 3待发货 4待收货 5待评价 6已完成 ,
        String url ="";
        switch (status){
            case -2:
                break;
            case -1:
                break;
            case 1:
                url = API.ORDERS_DETIAL+id+"/pay?"+"&access_token="+ UserInfoUtil.getInfoToken(getContext());
                break;
            case 2:
                break;
            case 3:
                url = API.ORDERS_DETIAL+id+"/remind/delivery?"+"&access_token="+ UserInfoUtil.getInfoToken(getContext());
                break;
            case 4:
                url = API.ORDERS_DETIAL+id+"/receipt?"+"&access_token="+ UserInfoUtil.getInfoToken(getContext());
                break;
            case 5:
                break;
            case 6:
                url = API.ORDERS_DETIAL+id+"/delete?"+"&access_token="+ UserInfoUtil.getInfoToken(getContext());
                break;
        }


        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        if(status == 1){
         int payment_type = itemData.getPayment_type();
         switch (payment_type){
             case 1: //ali
                 TypeToken<AliPayBeen> typeToken = new TypeToken<AliPayBeen>() {
                 };
                 OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<AliPayBeen>(typeToken) {
                     @Override
                     public void onError(Call call, Exception e, int id) {

                     }

                     @Override
                     public void onResponse(AliPayBeen response, int id) {
                         if(response.getErr_code() == 0){
                             doZFBzf( response.getAlipay());
                         }else {
                             showMsgToast(response.getErr_msg());
                         }
                     }
                 });
                 break;
             case 2://wx
                 TypeToken<WeiChatPayBeen> typeoken = new TypeToken<WeiChatPayBeen>() {
                 };
                 OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<WeiChatPayBeen>(typeoken) {
                     @Override
                     public void onError(Call call, Exception e, int id) {

                     }

                     @Override
                     public void onResponse(WeiChatPayBeen response, int id) {
                         if(response.getErr_code() == 0){
                             wxPay(response.getWechat());
                         }else {
                             showMsgToast(response.getErr_msg());
                         }
                     }
                 });
                 break;
             case 3://
                 TypeToken<UPPayBeen> typoken = new TypeToken<UPPayBeen>() {
                 };
                 OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<UPPayBeen>(typoken) {
                     @Override
                     public void onError(Call call, Exception e, int id) {

                     }

                     @Override
                     public void onResponse(UPPayBeen response, int id) {
                         if(response.getErr_code() == 0){
                             dpUPPay(response.getUnionpay());
                         }else {
                             showMsgToast(response.getErr_msg());
                         }
                     }
                 });
                 break;
         }
        }else {
            TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>(){};
            OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(ModelBeen response, int id) {
                    if(response.err_code == 0){
                        if(status == 3){
                            showMsgToast("提醒发货成功！");

                        }else if(status == 4){
                            showMsgToast("收货成功!");
                        }

                        else {
                            showMsgToast(response.err_msg);
                        }
                        queryData(true);
                    }else {
                        showMsgToast(response.err_msg);
                    }
                }
            });
        }

    }


    private void doZFBzf(final String orderSN) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(
                        getActivity());
                final Map<String, String> result = alipay
                        .payV2(orderSN, true);
                Log.i("msp", result.toString());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       // showMsgToast("result: "+result.toString());
                    }
                });
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void wxPay(WeiChatPayBeen.WechatBean wXpayResult){
        PayReq request = new PayReq();
        request.appId = wXpayResult.getAppid();
        request.partnerId = wXpayResult.getPartnerid();
        request.prepayId = wXpayResult.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wXpayResult.getNoncestr();
        request.timeStamp = wXpayResult.getTimestamp();
        request.sign = wXpayResult.getSign();
        iwxapi.registerApp(Constants.APP_ID);
        iwxapi.sendReq(request);
    }

    private void dpUPPay(String tn){

        UPPayAssistEx.startPay (getContext(), null, null, tn, "01");
    }


}
